'''Clue-less game driver file'''

import os.path as path
import os
import sys

if __name__ == '__main__':
    src = path.normpath(os.getcwd())
    shared = path.normpath(os.path.join(src, 'shared'))
    frontend = path.normpath(os.path.join(src, 'frontend'))
    backend  = path.normpath(os.path.join(src, 'backend'))

    for p in [src, shared, frontend, backend]:
        if p not in sys.path:
            sys.path.append(p)


import socket
import pickle
import threading

import Queue
import time
import game_constants
import game_thread
import server
import client
import proxy_receiver
import proxy_sender


            


def launch_thread(factory, *args):
    t = factory(*args)
    tq = t.in_q
    t.start()
    return (t, tq)

def join_thread((t, tq)):
    t.join

def ntfy(dest, *args):
    game_thread.GameThread.ntfy(dest[1], *args)


import threading
class SocketListener(threading.Thread):
    def __init__(self, server_q, addr, port):
        super(SocketListener, self).__init__()
        self.addr = addr
        self.port = port
        self.server_q = server_q
        self.clients = []
    
    def run(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((self.addr, self.port))
        s.listen(5)
        while(1):
            conn, addr = s.accept()
            print 'Connected by', addr
            p = proxy_receiver.ProxyReceiver(addr, self.server_q, conn)
            p.start()
            


def main(*args):
    
    addr_info = socket.getaddrinfo('', 50007) # Arbitrary non-privileged port

    print addr_info
    
    (family, socktype, proto, canonname, (addr, port)) =  addr_info[0]
    fqdn = socket.getfqdn()
    print 'Connect to server on: %s:%s' % (addr, port)
    


    (srv, srvq) = launch_thread(server.CluelessServer, 'server')

    sl = SocketListener(srvq, addr, port)
    sl.start()

    sl.join()
    srv.join()
    



if __name__ == '__main__':
    main(*sys.argv[1:])
